package com.aniu.cameramanager;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.preference.PreferenceManager;

import com.aniu.cameramanager.util.WorkTime;

public class CameraListenerService extends Service {
    private final String TAG = CameraListenerService.class.getSimpleName();

    private Notification mNotification = null;
    private int amStartWorkTime, amStopWorkTime, pmStartWorkTime, pmStopWorkTime;

    public CameraListenerService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mNotification = createNotification();
        startForeground(12306, mNotification);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(12306, mNotification);
        Log.i(TAG, "on create");
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        amStartWorkTime = sharedPreferences.getInt(WorkTime.AM_START_WORK_KEY, WorkTime.AM_START_WORK_DEFAULT_TIME);
        amStopWorkTime = sharedPreferences.getInt(WorkTime.AM_STOP_WORK_KEY, WorkTime.AM_STOP_WORK_DEFAULT_TIME);
        pmStartWorkTime = sharedPreferences.getInt(WorkTime.PM_START_WORK_KEY, WorkTime.PM_START_WORK_DEFAULT_TIME);
        pmStopWorkTime = sharedPreferences.getInt(WorkTime.PM_STOP_WORK_KEY, WorkTime.PM_STOP_WORK_DEFAULT_TIME);

        CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

        HandlerThread mBackgroundThread = new HandlerThread("CameraBackground");
        mBackgroundThread.start();
        Handler mBackgroundHandler = new Handler(mBackgroundThread.getLooper());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            manager.registerAvailabilityCallback(new CameraManager.AvailabilityCallback() {
                @Override
                public void onCameraAvailable(String cameraId) {
                    super.onCameraAvailable(cameraId);
                    Log.i(TAG, "camera available");
                }

                @Override
                public void onCameraUnavailable(String cameraId) {
                    super.onCameraUnavailable(cameraId);
                    Log.i(TAG, "camera unavailable");

                    if (WorkTime.isNowWorkTime(amStartWorkTime, amStopWorkTime, pmStartWorkTime, pmStopWorkTime)) {
                        Intent intent = new Intent(CameraListenerService.this, CameraBlockAlertActivity.class);
                        startActivity(intent);
                    }
                }
            }, mBackgroundHandler);
        }

        //如果系统在 onStartCommand() 返回后终止服务，则其会重建服务，并通过传递给服务的最后一个 Intent 调用 onStartCommand()。
//        return super.onStartCommand(intent, flags, startId);
        return START_REDELIVER_INTENT;
    }

    private static void createNotificationChannel(Context context) {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "camera_unavailable_name";
            String description = "camera_unavailable";
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel channel = new NotificationChannel( "camera_unavailable", name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

    private Notification createNotification() {
        createNotificationChannel(this);

        Intent fullScreenIntent = new Intent(this, CameraBlockAlertActivity.class);
        fullScreenIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
                | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
        PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
                fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, "camera_unavailable")
                        .setSmallIcon(R.drawable.ic_launcher_background)
                        .setContentTitle("Incoming call")
                        .setContentText("(919) 555-1234")
                        .setPriority(NotificationCompat.PRIORITY_MAX)
                        .setCategory(NotificationCompat.CATEGORY_CALL)

                        // Use a full-screen intent only for the highest-priority alerts where you
                        // have an associated activity that you would like to launch after the user
                        // interacts with the notification. Also, if your app targets Android 10
                        // or higher, you need to request the USE_FULL_SCREEN_INTENT permission in
                        // order for the platform to invoke this notification.
                        .setContentIntent(fullScreenPendingIntent)
                        .setFullScreenIntent(fullScreenPendingIntent, true);

        Notification incomingCallNotification = notificationBuilder.build();

        return incomingCallNotification;
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
}